/**
 * Method that get blog users list from server and display in 
 * the drop-down list, clean existing blogs if selection changes
 * @method getBloggers
 */
function getBloggers() {
	$.ajax({
		url:"scripts/proxyBlog.cgi",
		type:"get",
		data:"method=getBlogs&type=json",
		dataType:"json",
		success:function(data) {
			for(var i in data.Blogs) {
				var blog_user = data.Blogs[i];
				if(blog_user == "51158405") {
					$("#blog_users").append("<option value='" + blog_user + "' selected='selected'>" + blog_user + "</option>");
				}
				else {
					$("#blog_users").append("<option value='" + blog_user + "'>" + blog_user + "</option>");
				}
				blogusers.push(blog_user);
			}			
		},
		error:function(xhr, ajaxOptions, thrownError) {
			$("#blog_users").append("<option value='Error in Retrieving Blog Users'></option>");
			alert(xhr.status);
            alert(thrownError);
		}
	});
	
}

/**
 * append a blog in the content division
 * @method appendBlog
 * @param {Object}blog object blogpost
 */
function appendPost(post) {
	
	$("#content").prepend(
			"<div class='post' id='" + post.id + "'>" +
			"<div class='post_meta'>" +
			"<p class='author'>Author<span>" + post.author + "</span></p>" +
			"<p class='date'>Date<span>" + post.date + "</span><span>" + post.time + "</span></p>" +
			"</div><div class='post_content'><h2 class='title'>" + post.title + "</h2>" +
			"<p class='content'>" + post.content + "</p>" +
			"<div class='post_function'><a rel='" + post.id + "' class='edit_btn' href='#edit_popup'>Edit</a><a rel='" + post.id + "' class='delete_btn' href='#delete_popup'>Delete</a></div>" +
			"<div class='cleaner'></div></div><div class='cleaner'></div>"	// post id in href of edit and delete
			);
	
}


/**
 * Method that get all posts of a user from the server and display on the screen
 * @method getPost
 * @param {String}author The id of blog author
 */
function getPosts(author) {
	$.ajax({
		url:"scripts/proxyBlog.cgi",
		type:"get",
		data:"method=getPost&author=" + author + "&type=json",
		dataType:"json",
		beforeSend:function() {
			$("#content").html("");
			$("#loading").show();
		},
		success:function(data) {
			for(var i in data.BlogList) {
				
				var blog = data.BlogList[i];
				
				// format blog date & time
				var date_time = blog.updated.split('T');
				var date = date_time[0];
				var time = date_time[1].split('.')[0];
				
				// get data into the blogpost object
				var post = new blogpost(blog.id, blog.author, blog.title, blog.content, date, time);
				
				// add to blogposts array
				blogposts.push(post);
				
				// print in the content division
				appendPost(post); 
			}
			
			$("#loading").hide();
			// activate edit and delete button
			eventHandler();
		},
		error:function(xhr, ajaxOptions, thrownError) {
			$("#content").html("<h3>Error in retrieve blogs</h3>");
			alert(xhr.status);
            alert(thrownError);
		}
	});
}

/**
 * Method of handling post creation
 * @method createPost
*/ 
function createPost(author, password, title, content) {
	if( validateForm() == true ) {
		$.ajax({
			url:"scripts/createPost.cgi",
			type:"post",
			data:"username=" + author + "&password=" + password + "&title=" + title + "&content=" + content,
			beforeSend:function() {
				$("#create_loading").show();
			},
			success: function(data) {
				$("#create_loading").hide();
				getPosts(author);	// cannot use currentUser
			},
			error: function(xhr, ajaxOptions, thrownError) {
				$("#create_error").html("Incorrect Password.");
				alert(xhr.status);
	            alert(thrownError);
			}
		});
	}
	return false;
}


/**
 * Method of handling post editing
 * triggered when submit button is clicked and submit the form
 * @method editPost
 */
function editPost(author, password, title, content, id) {
	if( validateForm == true ) {
		$.ajax({
			url:"scripts/editPost.cgi",
			type:"post",
			data:"username=" + author + "&password=" + password + "&id=" + id + "&title=" + title + "&content=" + content,
			success:function(data) {
				closeEdit();
				getPosts(author);
			},
			error:function(xhr, ajaxOptions, thrownError) {
				$("#edit_error").html("Incorrect Password.");
				alert(xhr.status);
	            alert(thrownError);
			}
		});
	}
	else{
		return false;
	}
}

/**
 * Method of handling post deletion
 * @method deletePost
 */
function deletePost(author, password, id) {
	$.ajax({
		url:"scripts/deletePost.cgi",
		type:"post",
		data:"username=" + author + "&password=" + password + "&id=" + id,
		beforeSend:function() {
			
		},
		success:function(data) {
			$(post_id).hide("fast");
		},
		error:function(xhr, ajaxOptions, thrownError) {
            $("#delete_error").html("Incorrect Password.");
			alert(xhr.status);
            alert(thrownError);
		}
	});
}

/*
 * display blog post in a specific date
 * @method displayBlogByDate
 * @param {String}date the date selected in the calendar
 */
function displayBlogByDate(date) {
	
	$("#content").html("");
	
	// find blog posts of the date
	var length = 0;	// track the blog number
	for(var i in blogposts) {
		if(blogposts[i].date == date) {
			appendPost(blogposts[i]);
			length++;
		}
	}
	
	// if no match, show a message
	if (length == 0) {
		$("#content").prepend("<p>No post in this day.</p>");
	}
	
	// showing the title of selection
	$("#content").prepend("<h3>Blog of " + date + "</h3>" +
			"<a id='return' href='#'>Return to all posts&lt;&lt;</a>" +
			"<div class='cleaner_h20'></div>");
	
	// activate edit and delete button
	eventHandler();
}

/**
 * to render the blog calendar
 * @method calendar()
 */
function yui_calendar() {
	YUI().use('calendar', function (Y) {

		  Y.one('body').addClass('yui3-skin-sam');

		  // render the calendar
		  var calendar = new Y.Calendar({
		          contentBox: "#calendar_div",
		          height:'200px',
		          width:'200px',
		          showPrevMonth: true,
		          showNextMonth: true,
		          date: new Date()
		  }).render();
		  
		  // get a reference to Y.DataType.Date
		  var dtdate = Y.DataType.Date;
		  
		  // listen to calendar's selectionChange event
		  calendar.on("selectionChange", function(ev) {
			  var newDate = dtdate.format(ev.newSelection[0]);
			  displayBlogByDate(newDate);
		  });

	});
}

/*
function yui_autocomplete() {	
	YUI().use('autocomplete', 'autocomplete-filters', 'autocomplete-highlighters', function (Y) {
		
		Y.one('#create_user').plug(Y.Plugin.AutoComplete, {
			resultFilters: 'Blogs',
			//resultHighlighter: 'phraseMatch',
			source: blogusers
		});
	});
}*/